package com.lazyking.nio.work1;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

public class NioServer {
    public static void main(final String[] args) throws IOException {
        //1.创建sokect连接通道
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        //2.配置通道监听地址和模式
        socketChannel.socket().bind(new InetSocketAddress(8888));
        socketChannel.configureBlocking(true);
        //3.监听客户端

        while (true) {
            //4.当有连接时,无连接时，accept方法阻塞程序，有连接时返回连接对象
            SocketChannel socketChannel1 = socketChannel.accept();
            //5.设置缓冲区大小1024
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            //6.从连接中读数据到缓冲区,返回值为字节数量
            try {
                int read = socketChannel1.read(byteBuffer);
                while (read != -1) {
                    byteBuffer.flip();
                    System.out.println(StandardCharsets.UTF_8.decode(byteBuffer));
                    byteBuffer.clear();
                    read = socketChannel1.read(byteBuffer);
                }
            }
            catch (IOException e) {
                System.err.println("异常："+e.getMessage());
            }
            socketChannel1.close();
        }


    }
}
